package dao

import (
	"database/sql/driver"
	"encoding/json"
	"fmt"
	"time"
)

type ModelTime struct {
	CreatedAt Time  `json:"createdAt"`
	UpdatedAt Time  `json:"updatedAt"`
	DeletedAt *Time `json:"deletedAt" sql:"index"`
}

type ModelAuth struct {
	UpdatedBy string `json:"updatedBy" gorm:"comment:更新者;"`
	CreatedBy string `json:"createdBy" gorm:"comment:创建者;"`
}

// jtime format json time field by myself
type Time struct {
	time.Time
}

// MarshalJSON on JSONTime format Time field with %Y-%m-%d %H:%M:%S
func (t Time) MarshalJSON() ([]byte, error) {
	formatted := fmt.Sprintf("\"%s\"", t.Format("2006-01-02 15:04:05"))
	return []byte(formatted), nil
}

// Value insert timestamp into mysql need this function.
func (t Time) Value() (driver.Value, error) {
	var zeroTime time.Time
	if t.Time.UnixNano() == zeroTime.UnixNano() {
		return nil, nil
	}
	return t.Time, nil
}

// Scan valueof time.Time
func (t *Time) Scan(v interface{}) error {
	value, ok := v.(time.Time)
	if ok {
		*t = Time{Time: value}
		return nil
	}
	return fmt.Errorf("can not convert %v to timestamp", v)
}

type StringArray []string

func (p StringArray) Value() (driver.Value, error) {
	return json.Marshal(p)
}

func (p *StringArray) Scan(data interface{}) error {
	return json.Unmarshal(data.([]byte), &p)
}

type UintArray []uint

// Value insert
func (j UintArray) Value() (driver.Value, error) {
	return json.Marshal(&j)
}

// Scan valueof
func (t *UintArray) Scan(v interface{}) error {
	return json.Unmarshal(v.([]byte), t)
}
